﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics;

namespace SSFT
{
	public class ProgressInfo
	{
		string		m_filename;
		long		m_filesize;

		long		curr_transferred;
		long		last_transferred;
		List<float>	speeds;
		int			speeds_i;
		Stopwatch	last_elapsed;

		const int	ListSize = 20;

		public ProgressInfo()
		{
			curr_transferred = 0;
			speeds = new List<float>(ListSize);
			speeds_i = 0;
			last_elapsed = new Stopwatch();
		}

		public string Filename
		{
			get { return m_filename; }
			set { m_filename = value; }
		}
		public long Filesize
		{
			get { return m_filesize; }
			set { m_filesize = value; }
		}
		public long BytesTransferred
		{
			get { return curr_transferred; }
			set { curr_transferred = value; }
		}

		public float Percent
		{
			get
			{
				return ((float)curr_transferred /
					(float)m_filesize) * 100.0f;
			}
		}

		public float BytesPerSecond
		{
			get
			{
				float bytes_per_sec;

				// Check if the stopwatch is running.
				if (!last_elapsed.IsRunning)
				{
					last_elapsed.Reset();
					last_elapsed.Start();
					return 0;
				}

				// Calculate the speed for this benchmark.
				last_elapsed.Stop();
				bytes_per_sec =
					(float)(curr_transferred - last_transferred) /
					(float)(last_elapsed.Elapsed.TotalSeconds);

				// Add speed to list or overwrite old entry.
				if (speeds_i < speeds.Count)
					speeds[speeds_i] = bytes_per_sec;
				else
					speeds.Add(bytes_per_sec);
				speeds_i = (speeds_i + 1) % ListSize;
	
				// Start a new benchmark.
				last_transferred = curr_transferred;
				last_elapsed.Reset();
				last_elapsed.Start();

				// Speed is average of several speed benchmarks.
				return speeds.Average();
			}
		}
	}
}